using System;
using System.Web;
using Microsoft.Practices.ServiceLocation;
using NHibernate.Context;
using ThunderJob.Bootstrapper.Dependency;
using ThunderJob.Bootstrapper.Extensions;
using NHibernate;
using ThunderJob.Persistence;

namespace ThunderJob.Bootstrapper.Modules
{
    public class NHibernateModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += ContextBeginRequest;
            context.EndRequest += ContextEndRequest;
        }

        private void ContextBeginRequest(object sender, EventArgs e)
        {
            if (!HttpContext.Current.Request.IsStaticFile())
            {
                var session = NHibernateSession.CreateInStorage();
                session.BeginTransaction();
            }
        }

        private void ContextEndRequest(object sender, EventArgs e)
        {
            var session = NHibernateSession.DeleteFromStorage();
            if (session != null)
            {
                if (session.Transaction != null && session.Transaction.IsActive)
                {
                    try
                    {
                        session.Transaction.Commit();
                    }
                    catch (Exception)
                    {
                        session.Transaction.Rollback();
                        throw;
                    }
                    finally
                    {
                        session.Transaction.Dispose();
                        session.Dispose();
                    }
                }
                
            }
        }

        public void Dispose() { }
    }
}